package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

//    @SneakyThrows
//    public boolean isExclude() {
//        String requestURI = request.getRequestURI();
//        if(requestURI.startsWith("/member")) {
//            return true;
//        }
//        return false;
//    }
    @Override
    public void insertFill(MetaObject metaObject) {
         this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("createBy", String.valueOf(getLoginUser()), metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", String.valueOf(getLoginUser()), metaObject);

//        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
//        this.strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(getLoginUser()));
    }

    public Long getLoginUser() {


        try {
            //1.后台管理系统
            //2.小程序新增和修改时都会用到自动填充 UserThreadLocal.getUserId()
            //定时任务
            //操作日志异步
            //消息消费者

            //在放入token时，放入userthreadlocal。因为是过滤器，所以在dofilter之后要清空线程，避免内存泄露

            return UserThreadLocal.getUserId() == null ? 1L : UserThreadLocal.getUserId() ;
        } catch (Exception e) {
            return 1L;
        }
    }
}
